package com.example.deploysinggle.test1.common.redis.impl;

import com.example.deploysinggle.test1.common.redis.CacheService;
import com.example.deploysinggle.test1.common.util.JsonUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO 缓存方法
 * @date 2024/12/15 19:32
 */
@Service
public class CacheServiceImpl implements CacheService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public <T> T get(String key, Class<T> clazz) {
        return Optional.ofNullable(redisTemplate.opsForValue().get(key))
                .map(s -> JsonUtil.jsonToObject(s, clazz))
                .orElse(null);
    }

    @Override
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    @Override
    public String get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    @Override
    public void set(String key, Object value, Long time) {
        redisTemplate.opsForValue().set(key, JsonUtil.toJson(value), time, TimeUnit.MILLISECONDS);
    }

    @Override
    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, JsonUtil.toJson(value));
    }

    @Override
    public Long increment(String key, long delta) {
        if (Boolean.TRUE.equals(hasKey(key))){
            redisTemplate.opsForValue().increment(key, delta);
        }
        return null;
    }

    @Override
    public <T> List<T> getList(String key, TypeReference<List<T>> typeReference) {
        return Optional.ofNullable(redisTemplate.opsForValue().get(key))
                .map(s -> JsonUtil.jsonToList(s, typeReference))
                .orElse(null);
    }
}
